package com.supermarket.ui;

import com.supermarket.dao.UserDAO;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 用户注册界面 - 现代化设计
 * 美观的Swing界面实现
 */
public class RegisterFrame extends JFrame {

    private JTextField usernameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JTextField realNameField;
    private JTextField phoneField;
    private JTextField emailField;
    private JButton registerButton;
    private JButton backButton;
    private JLabel statusLabel;
    private UserDAO userDAO;
    private LoginFrame parentFrame;

    public RegisterFrame(LoginFrame parent) {
        this.parentFrame = parent;
        this.userDAO = new UserDAO();
        initializeComponents();
        setupLayout();
        setupEventListeners();
        setFrameProperties();
    }

    /**
     * 初始化组件
     */
    private void initializeComponents() {
        // 创建组件
        usernameField = createStyledTextField("请输入用户名");
        passwordField = createStyledPasswordField("请输入密码");
        confirmPasswordField = createStyledPasswordField("请确认密码");
        realNameField = createStyledTextField("请输入真实姓名");
        phoneField = createStyledTextField("请输入手机号");
        emailField = createStyledTextField("请输入邮箱地址");
        registerButton = createStyledButton("注册", new Color(40, 167, 69));
        backButton = createStyledButton("返回登录", new Color(108, 117, 125));
        statusLabel = new JLabel("", JLabel.CENTER);

        // 设置字体和样式
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 14);
        Font buttonFont = new Font("微软雅黑", Font.BOLD, 14);
        Font smallFont = new Font("微软雅黑", Font.PLAIN, 12);

        usernameField.setFont(labelFont);
        passwordField.setFont(labelFont);
        confirmPasswordField.setFont(labelFont);
        realNameField.setFont(labelFont);
        phoneField.setFont(labelFont);
        emailField.setFont(labelFont);
        registerButton.setFont(buttonFont);
        backButton.setFont(buttonFont);
        statusLabel.setFont(smallFont);
        statusLabel.setForeground(new Color(220, 53, 69));

        // 设置组件大小
        Dimension fieldSize = new Dimension(280, 40);
        usernameField.setPreferredSize(fieldSize);
        passwordField.setPreferredSize(fieldSize);
        confirmPasswordField.setPreferredSize(fieldSize);
        realNameField.setPreferredSize(fieldSize);
        phoneField.setPreferredSize(fieldSize);
        emailField.setPreferredSize(fieldSize);
        registerButton.setPreferredSize(new Dimension(120, 40));
        backButton.setPreferredSize(new Dimension(120, 40));
    }

    /**
     * 创建样式化文本框
     */
    private JTextField createStyledTextField(String placeholder) {
        JTextField field = new JTextField();
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)));
        field.setBackground(Color.WHITE);
        field.setForeground(new Color(73, 80, 87));
        return field;
    }

    /**
     * 创建样式化密码框
     */
    private JPasswordField createStyledPasswordField(String placeholder) {
        JPasswordField field = new JPasswordField();
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)));
        field.setBackground(Color.WHITE);
        field.setForeground(new Color(73, 80, 87));
        return field;
    }

    /**
     * 创建样式化按钮
     */
    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setBackground(backgroundColor);
        button.setForeground(Color.BLACK);
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(backgroundColor.darker());
                button.setForeground(Color.BLACK);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(backgroundColor);
                button.setForeground(Color.BLACK);
            }
        });

        return button;
    }

    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout());
        getContentPane().setBackground(new Color(248, 249, 250));

        // 主面板
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBackground(Color.WHITE);
        mainPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(30, 40, 30, 40)));

        GridBagConstraints gbc = new GridBagConstraints();

        // 标题
        JLabel titleLabel = new JLabel("用户注册", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(52, 144, 220));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(0, 0, 30, 0);
        mainPanel.add(titleLabel, gbc);

        // 副标题
        JLabel subtitleLabel = new JLabel("创建新账户", JLabel.CENTER);
        subtitleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        subtitleLabel.setForeground(new Color(108, 117, 125));
        gbc.gridy = 1;
        gbc.insets = new Insets(0, 0, 25, 0);
        mainPanel.add(subtitleLabel, gbc);

        // 用户名
        JLabel usernameLabel = new JLabel("用户名");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(usernameLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 15, 0);
        mainPanel.add(usernameField, gbc);

        // 密码
        JLabel passwordLabel = new JLabel("密码");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        passwordLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(passwordLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 15, 0);
        mainPanel.add(passwordField, gbc);

        // 确认密码
        JLabel confirmPasswordLabel = new JLabel("确认密码");
        confirmPasswordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        confirmPasswordLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(confirmPasswordLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 7;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 15, 0);
        mainPanel.add(confirmPasswordField, gbc);

        // 真实姓名
        JLabel realNameLabel = new JLabel("真实姓名");
        realNameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        realNameLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 8;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(realNameLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 9;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 15, 0);
        mainPanel.add(realNameField, gbc);

        // 手机号
        JLabel phoneLabel = new JLabel("手机号");
        phoneLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        phoneLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 10;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(phoneLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 11;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 15, 0);
        mainPanel.add(phoneField, gbc);

        // 邮箱
        JLabel emailLabel = new JLabel("邮箱地址");
        emailLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        emailLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 12;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(emailLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 13;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 25, 0);
        mainPanel.add(emailField, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setBackground(Color.WHITE);
        buttonPanel.setOpaque(false);
        buttonPanel.add(registerButton);
        buttonPanel.add(backButton);

        gbc.gridx = 0;
        gbc.gridy = 14;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(0, 0, 20, 0);
        mainPanel.add(buttonPanel, gbc);

        // 状态标签
        gbc.gridy = 15;
        gbc.insets = new Insets(0, 0, 0, 0);
        mainPanel.add(statusLabel, gbc);

        // 居中显示
        JPanel centerPanel = new JPanel(new GridBagLayout());
        centerPanel.setBackground(new Color(248, 249, 250));
        GridBagConstraints centerGbc = new GridBagConstraints();
        centerGbc.gridx = 0;
        centerGbc.gridy = 0;
        centerPanel.add(mainPanel, centerGbc);

        add(centerPanel, BorderLayout.CENTER);
    }

    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 注册按钮点击事件
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performRegister();
            }
        });

        // 返回按钮点击事件
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                backToLogin();
            }
        });

        // 回车键注册
        emailField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performRegister();
            }
        });
    }

    /**
     * 设置窗口属性
     */
    private void setFrameProperties() {
        setTitle("超市管理系统 - 用户注册");
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setResizable(false);
        setSize(500, 800);
        setLocationRelativeTo(null); // 窗口居中

        // 设置关闭操作
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                backToLogin();
            }
        });

        // 设置系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception ignored) {
        }
    }

    /**
     * 执行注册
     */
    private void performRegister() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        String realName = realNameField.getText().trim();
        String phone = phoneField.getText().trim();
        String email = emailField.getText().trim();

        // 表单验证
        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() ||
                realName.isEmpty() || phone.isEmpty() || email.isEmpty()) {
            statusLabel.setText("请填写所有必填字段");
            statusLabel.setForeground(Color.RED);
            return;
        }

        if (!password.equals(confirmPassword)) {
            statusLabel.setText("两次输入的密码不一致");
            statusLabel.setForeground(Color.RED);
            return;
        }

        if (password.length() < 6) {
            statusLabel.setText("密码长度不能少于6位");
            statusLabel.setForeground(Color.RED);
            return;
        }

        if (!isValidPhone(phone)) {
            statusLabel.setText("手机号格式不正确");
            statusLabel.setForeground(Color.RED);
            return;
        }

        if (!isValidEmail(email)) {
            statusLabel.setText("邮箱格式不正确");
            statusLabel.setForeground(Color.RED);
            return;
        }

        // 显示注册中状态
        statusLabel.setText("正在注册...");
        statusLabel.setForeground(Color.BLUE);
        registerButton.setEnabled(false);

        try {
            boolean success = userDAO.register(username, password, realName, phone, email);
            if (success) {
                statusLabel.setText("注册成功！请使用新账号登录");
                statusLabel.setForeground(Color.BLUE);

                JOptionPane.showMessageDialog(this,
                        "注册成功！\n用户名：" + username + "\n角色：收银员\n请返回登录页面使用新账号登录。",
                        "注册成功", JOptionPane.INFORMATION_MESSAGE);

                // 延迟后返回登录界面
                Timer timer = new Timer(1000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        backToLogin();
                    }
                });
                timer.setRepeats(false);
                timer.start();

            } else {
                statusLabel.setText("注册失败：用户名已存在");
                statusLabel.setForeground(Color.RED);
            }
        } catch (Exception ex) {
            statusLabel.setText("注册失败：" + ex.getMessage());
            statusLabel.setForeground(Color.RED);
        } finally {
            registerButton.setEnabled(true);
        }
    }

    /**
     * 返回登录界面
     */
    private void backToLogin() {
        this.setVisible(false);
        parentFrame.showLoginFrame();
        this.dispose();
    }

    /**
     * 验证手机号格式
     */
    private boolean isValidPhone(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        return email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
    }
}
